package xgorm

import (
	"reflect"
	"strings"
)

type Model interface {
	TableName() string
}

func ModelToMap(m Model) map[string]any {
	t := reflect.TypeOf(m)
	if t.Kind() == reflect.Ptr {
		t = t.Elem()
	}

	if t.Kind() != reflect.Struct {
		return nil
	}

	v := reflect.ValueOf(m)
	if v.Kind() == reflect.Ptr {
		v = v.Elem()
	}

	data := make(map[string]any)
	for i := 0; i < t.NumField(); i++ {
		field := t.Field(i)
		key := field.Name
		if tag := field.Tag.Get("gorm"); strings.Contains(tag, "column") {
			arr := strings.Split(tag, ";")
			for _, av := range arr {
				if strings.Contains(av, "column") {
					key = strings.ReplaceAll(av, "column:", "")
					break
				}
			}
		}
		data[key] = v.Field(i).Interface()
	}
	return data

}

func ModelToMapWithTag(m Model, tag string) map[string]any {
	t := reflect.TypeOf(m)
	if t.Kind() == reflect.Ptr {
		t = t.Elem()
	}

	if t.Kind() != reflect.Struct {
		return nil
	}

	v := reflect.ValueOf(m)
	if v.Kind() == reflect.Ptr {
		v = v.Elem()
	}

	data := make(map[string]any)
	for i := 0; i < t.NumField(); i++ {
		field := t.Field(i)
		key := field.Tag.Get(tag)
		if key == "" || key == "-" {
			continue
		}
		keyArr := strings.Split(key, ",")
		key = keyArr[0]
		data[key] = v.Field(i).Interface()
	}
	return data
}
